<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <el-form
      class="form"
      :model="basicForm"
      label-position="top"
      :rules="basicRules"
      ref="basicFormRef"
    >
      <div class="body">
        <div class="body-left">
          <div class="project">
            <!-- 基本信息 -->
            <div class="project-part">
              <div class="project-part-title">基本信息</div>

              <el-form-item label="事件名称" prop="title">
                <el-input
                  v-model="basicForm.title"
                  placeholder="请输入"
                  :disabled="isDetail"
                ></el-input>
              </el-form-item>

              <el-form-item label="事件地点">
                <el-input
                  v-model="basicForm.eventAddress"
                  placeholder="请输入"
                  :disabled="isDetail"
                ></el-input>
              </el-form-item>

              <el-form-item label="事件时间">
                <el-date-picker
                  v-model="basicForm.eventTime"
                  type="date"
                  :disabled="isDetail"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>

              <el-form-item label="参与部门">
                <el-cascader
                  v-model="basicForm.joinPeople"
                  :options="options"
                  :props="props"
                  :append-to-body="false"
                  collapse-tags
                  :disabled="isDetail"
                  clearable
                >
                </el-cascader>
              </el-form-item>

              <el-form-item label="查看权限">
                <el-checkbox-group
                  v-model="basicForm.roleIdPri"
                  :disabled="isDetail"
                  class="checkbox-group"
                >
                  <el-checkbox
                    v-for="item in departmentRoleOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                    class="checkbox-item"
                  >
                    {{ item }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <!-- <el-form-item
                label="查看部门"
                v-if="
                  basicForm.roleIdPri &&
                  basicForm.roleIdPri.includes('部门')
                "
              >
                <el-checkbox-group
                  v-model="basicForm.departName"
                  :disabled="isDetail"
                >
                  <el-checkbox
                    v-for="item in departmentViewOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                    {{ item }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item> -->

              <!-- <el-form-item
                label="事件图片(1-2张)"
                prop="policySixOne"
              >
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-success="handleAvatarSuccess"
                  :file-list="fileList"
                  list-type="picture"
                >
                  <div class="uploadBox">
                    <i
                      class="el-icon-plus avatar-uploader-icon"
                    ></i>
                    <div>点击上传图片</div>
                  </div>
                </el-upload>
              </el-form-item> -->

              <el-form-item label="事件图片(1-2张)">
                <el-upload
                  class="upload-image"
                  action=""
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleChangeImage"
                  :on-remove="handleRemoveImage"
                  :on-preview="handlePreviewImage"
                  :show-file-list="true"
                  :file-list="fileList"
                  v-if="!isDetail"
                  multiple
                  accept="image/*"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>

                <el-dialog
                  :visible.sync="previewVisible"
                  width="50%"
                  v-if="!isDetail"
                >
                  <img
                    :src="previewImage"
                    alt="预览"
                    style="width: 100%"
                  />
                </el-dialog>
                <el-image
                  v-for="item in fileList"
                  :preview-src-list="previewImageList"
                  :key="item.url"
                  :src="item.url"
                  v-if="isDetail"
                  class="image"
                >
                </el-image>
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="body-right">
          <el-form-item label="事件内容">
            <el-input
              v-model="basicForm.eventContent"
              placeholder="请输入"
              type="textarea"
              :disabled="isDetail"
              :rows="20"
            ></el-input>
          </el-form-item>

          <el-form-item label="事件备注">
            <el-input
              v-model="basicForm.description"
              placeholder="请输入存在问题、解决措施、下一步工作计划等"
              type="textarea"
              :disabled="isDetail"
              :rows="3"
            ></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  departmentRoleOptions,
  departmentViewOptions
} from '@/utils/project/data'
import dayjs from 'dayjs'
import {
  addImportantEvent,
  uploadFileById,
  queryImportantEventById
} from '@/api/dataManagement'
import { roleQuery } from '@/api/role'
import { STATIC_FILE_URL } from '@/api/config.js'
import { getDeptTree } from '@/api/dept'

export default {
  props: {
    pkid: String,
    title: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        title: '',
        eventTime: '',
        eventAddress: '',
        joinPeople: [],
        eventContent: '',
        roleIdPri: [],
        departName: '',
        description: ''
      },
      checkList: [],
      loading: false,
      options: [],
      basicRules: {
        title: [
          {
            required: true,
            message: '请输入事件名称',
            trigger: 'blur'
          }
        ]
      },
      dialogImageVisible: false,
      dialogImageUrl: '',
      fileList: [],
      // props: {
      //   value: 'pkid',
      //   label: 'deptName',
      //   children: 'childTree'
      // },
      props: {
        value: 'deptName',
        label: 'deptName',
        children: 'childTree',
        multiple: true
      },
      uploadFileList: [],
      roleList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: []
    }
  },
  computed: {
    titles() {
      return [this.$route.query.title]
    },
    departmentRoleOptions() {
      return departmentRoleOptions
    },
    departmentViewOptions() {
      return departmentViewOptions
    }
  },
  watch: {},
  mounted() {
    this.getTreeList()
    this.getRoleList()
    if (this.pkid) {
      this.getDetailInfo()
    }
  },
  methods: {
    getTreeList() {
      getDeptTree().then((res) => {
        if (res.success) {
          const targetPkids =
            process.env.NODE_ENV == 'production'
              ? [
                  '1db54341d27e4942a06395dad8ac05a4',
                  'ad1c41ce58ac4b5d94235e242f5a87ed'
                ]
              : ['13f8f9c7a6644526a2d1a0909960e9f9', 'new']
          const target = res.data[0].childTree.filter(
            // (i) => i.deptName === '科技城发展局'
            (i) => targetPkids.includes(i.pkid)
          )

          if (target) {
            this.options = this.removeEmptyChildTree(target)
          } else {
            this.options = []
          }
        }
      })
    },
    removeEmptyChildTree(nodes) {
      return nodes
        .map((node) => {
          if (Array.isArray(node.childTree)) {
            node.childTree = this.removeEmptyChildTree(
              node.childTree
            )
            if (node.childTree.length === 0) {
              delete node.childTree
            }
          }
          return node
        })
        .filter((node) => {
          return (
            !node.childTree ||
            (Array.isArray(node.childTree) &&
              node.childTree.length > 0)
          )
        })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 获取项目详情
    getDetailInfo() {
      this.loading = true
      queryImportantEventById(this.pkid).then((res) => {
        if (res.success) {
          const data = res.data
          this.basicForm = data
          if (data.joinPeople) {
            this.basicForm.joinPeople =
              data.joinPeople.split(';')
          } else {
            this.basicForm.joinPeople = []
          }

          if (data.roleIdPri) {
            const arr = data.roleIdPri.split(',')
            this.basicForm.roleIdPri =
              this.matchRoleName(arr)
          } else {
            this.basicForm.roleIdPri = []
          }

          if (
            data.resourceFileInfos &&
            data.resourceFileInfos.length
          ) {
            this.fileList = data.resourceFileInfos.map(
              (item) => {
                return {
                  ...item,
                  url: `${STATIC_FILE_URL}${item.filePath}`
                }
              }
            )

            if (this.isDetail) {
              this.previewImageList = this.fileList.map(
                (item) => item.url
              )
            }

            this.uploadFileList = JSON.parse(
              JSON.stringify(this.fileList)
            )
          }
        }
        this.loading = false
      })
    },

    getRoleList() {
      const params = {
        pageIndex: 1,
        pageSize: 999
      }

      roleQuery(params).then((res) => {
        if (res.success) {
          this.roleList = res.data.list
        }
      })
    },

    // 保存信息
    saveInfo() {
      this.basicForm?.roleIdPri?.length
        ? (this.basicForm.roleIdPri = this.matchRoleId(
            this.basicForm.roleIdPri
          ))
        : (this.basicForm.roleIdPri = '')

      console.log(
        'joinPeople multiple: ',
        this.basicForm.joinPeople
      )
      if (this.basicForm.joinPeople) {
        this.basicForm.joinPeople =
          this.basicForm.joinPeople.join(';')
      } else {
        this.basicForm.joinPeople = ''
      }

      if (this.basicForm.eventTime) {
        this.basicForm.eventTime = dayjs(
          this.basicForm.eventTime
        ).format('YYYY-MM-DD')
      } else {
        this.basicForm.eventTime = ''
      }

      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          this.loading = true
          const currentUpload = this.uploadFileList.filter(
            (i) => !i.pkid
          )
          const isUploadImage = this.uploadFileList
            .filter((i) => i.pkid)
            .map((item) => item.pkid)

          const uploadPromises = currentUpload.map(
            (file) => {
              const image = new FormData()
              image.append('file', file)
              return uploadFileById(image)
            }
          )

          Promise.all(uploadPromises)
            .then((results) => {
              const allSuccess = results.every(
                (res) => res.success
              )

              if (!allSuccess) {
                this.$message.error('部分图片上传失败')
                return
              }

              let imageArr = results.map(
                (item) => item.data
              )
              this.basicForm.picture = imageArr
                .concat(isUploadImage)
                .join(',')

              if (this.pkid) {
                this.basicForm.resourceFileInfos = null
              }
              addImportantEvent(this.basicForm).then(
                (res) => {
                  this.loading = false
                  if (res.success) {
                    this.$message.success(
                      this.pkid ? '编辑成功' : '保存成功'
                    )
                    this.$router.push({
                      path: '/dataManagement/importantEvent/list',
                      query: { refresh: Date.now() }
                    })
                  } else {
                    this.$message.error(res.message)
                  }
                  this.loading = false
                }
              )
            })
            .catch((err) => {
              this.loading = false
              this.$message.error('图片上传出错')
              console.error(err)
            })
        }
      })
    },

    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    // 匹配角色列表id
    matchRoleId(arr) {
      let result = []
      arr.forEach((item) => {
        const obj = this.roleList.find(
          (i) => item === i.roleName
        )
        if (obj) {
          result.push(obj.pkid)
        }
      })
      if (result.length) {
        return result.join(',')
      }
    },

    // 根据id匹配角色列表名称
    matchRoleName(arr) {
      let result = []
      arr.forEach((item) => {
        const obj = this.roleList.find(
          (i) => item === i.pkid
        )
        if (obj) {
          result.push(obj.roleName)
        }
      })
      if (result.length) {
        return result
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 10px;
  overflow-y: auto;

  .form {
    flex: 1;
    padding-bottom: 100px;
    overflow-y: auto;

    .body {
      flex: 1;
      display: flex;
      padding: 10px 0 0 20px;

      &-left {
        width: 49%;
        border-right: 1px solid #f1f1f1;
        overflow: scroll;
        z-index: 2;
      }

      &-right {
        flex: 1;
        padding-left: 10px;
        padding-right: 10px;
      }

      .top {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        padding-right: 10px;
      }
    }
  }

  .line {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    border-top: 1px solid #eee;
    padding: 10px 0;
    display: flex;
    justify-content: center;
    z-index: 10;
  }
}

::v-deep .el-checkbox-group {
  width: 450px;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.checkbox-item {
  width: 25%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-textarea {
  width: 100% !important;
  .el-textarea__inner {
    width: 100% !important;
  }
}
::v-deep .avatar-uploader {
  display: flex;
  .el-upload-list {
    display: flex;
    li {
      width: 140px;
      height: 140px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 0 10px;
      img {
        width: 100px;
        height: 100px;
      }
      .el-upload-list__item-name {
        position: absolute;
        bottom: 10px;
        display: none;
      }
    }
  }
}
::v-deep .uploadBox {
  width: 140px;
  height: 140px;
  background: #eeeeee;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  div {
    font-size: 14px;
  }
}

::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep
  .el-upload-list--picture-card
  .el-upload-list__item {
  width: 100px;
  height: 100px;
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
</style>
